from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.hashers import check_password
from django.utils import timezone
from ..models import Examinee
from ..forms import RegisterForm, LoginForm

def register(request):
    """考生注册视图"""
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            phone = form.cleaned_data['phone']
            name = form.cleaned_data['name']
            password = form.cleaned_data['password']
            confirm_password = form.cleaned_data['confirm_password']
            email = form.cleaned_data['email']
            gender = form.cleaned_data['gender']
            organization = form.cleaned_data['organization']
            id_card = form.cleaned_data['id_card']

            # 验证密码
            if password != confirm_password:
                messages.error(request, '两次输入的密码不一致')
                return render(request, 'exam_system/register.html', {'form': form})

            # 验证手机号是否已被注册
            if Examinee.objects.filter(phone=phone).exists():
                messages.error(request, '该手机号已被注册')
                return render(request, 'exam_system/register.html', {'form': form})

            try:
                # 创建考生账号
                examinee = Examinee.objects.create(
                    phone=phone,
                    name=name,
                    password=password,  # 模型的save方法会自动处理密码加密
                    email=email,
                    gender=gender,
                    organization=organization,
                    id_card=id_card
                )
                messages.success(request, '注册成功，请登录')
                return redirect('exam_system:login')
            except Exception as e:
                messages.error(request, f'注册失败：{str(e)}')
                return render(request, 'exam_system/register.html', {'form': form})
        else:
            # 如果表单无效，显示错误信息
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f'{field}: {error}')
    else:
        form = RegisterForm()

    return render(request, 'exam_system/register.html', {'form': form})

def login(request):
    """考生登录视图"""
    # 检查是否需要显示验证码
    show_captcha = request.session.get('login_attempts', 0) >= 3

    if request.method == 'POST':
        form = LoginForm(request.POST)

        # 如果需要验证码但表单中没有验证码字段，则设置为必需
        if show_captcha:
            form.fields['captcha'].required = True

        if form.is_valid():
            phone = form.cleaned_data['phone']
            password = form.cleaned_data['password']

            try:
                examinee = Examinee.objects.get(phone=phone)
                if check_password(password, examinee.password):
                    # 更新最后登录时间
                    examinee.last_login = timezone.now()
                    examinee.save()

                    # 在session中存储考生信息
                    request.session['examinee_id'] = examinee.id
                    request.session['examinee_name'] = examinee.name

                    # 重置登录失败次数
                    request.session['login_attempts'] = 0

                    messages.success(request, '登录成功')
                    return redirect('exam_system:dashboard')
                else:
                    messages.error(request, '密码错误')
                    # 增加登录失败次数
                    request.session['login_attempts'] = request.session.get('login_attempts', 0) + 1
            except Examinee.DoesNotExist:
                messages.error(request, '该手机号未注册')
                # 增加登录失败次数
                request.session['login_attempts'] = request.session.get('login_attempts', 0) + 1
            except Exception as e:
                messages.error(request, f'登录失败：{str(e)}')
                # 增加登录失败次数
                request.session['login_attempts'] = request.session.get('login_attempts', 0) + 1
    else:
        form = LoginForm()
        # 如果需要验证码，确保表单字段设置为必需
        if show_captcha:
            form.fields['captcha'].required = True

    return render(request, 'exam_system/login.html', {'form': form, 'show_captcha': show_captcha})

def logout(request):
    """考生登出视图"""
    request.session.flush()
    messages.success(request, '已安全退出')
    return redirect('exam_system:login')